import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import router from '../router'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API // api 的 base_url
  // timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken('token') && getToken('id')) {
      config.headers['token'] = getToken('token')
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === '0') {
      return res
    } else if (res.code === '10002') { // 1002: token无效
      MessageBox.alert('请重新登录', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          store.dispatch('LogOut').then(() => {
            location.reload()
          })
        }
      })
    } else if (res.code === '4002') { // 4002: 未设置支付密码
      MessageBox.alert(res.msg, '', {
        confirmButtonText: '确定',
        callback: action => {
          router.push('/setting/pwdpay')
        }
      })
    } else {
      Message({
        message: res.msg,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject('error')
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
